<!-- 课程内容的录制 -->
<template>
  <div>
    <page-header content="课程内容" @back="goBack()"></page-header>
    <!-- 课程录制-->
    <div>
      <el-progress :percentage="progress"></el-progress>
      <div class="record">
        <div class="record-play">
          <audio id="audioVoice" controls autoplay hidden></audio>
        </div>
      </div>
      <div class="display">
        <div>
          <el-button v-if="!isFinished" @click="onStartVoice">开始</el-button>
          <el-button v-else @click="onEndVoice" type="danger" plain
            >结束</el-button
          >
        </div>
        <div>
          <el-button
            v-if="ifDisplay"
            type="warning"
            plain
            @click="stopDispaly()"
            >暂停</el-button
          >
          <el-button v-else plain @click="onPlayAudio()" type="warning"
            >播放</el-button
          >
        </div>

        <div>
          <el-button @click="uploadFile" type="success">上传</el-button>
        </div>
      </div>
    </div>

    <div class="container">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <el-row :gutter="10">
                <el-col :span="12"><el-button>源代码</el-button></el-col>
                <el-col :span="12">
                  <el-button
                    type="primary"
                    class="submitBIN"
                    @click="runHtml()"
                  >
                    开始运行
                  </el-button>
                </el-col>
              </el-row>
            </div>
            <div class="card_body">
              <textarea ref="HtmlEditor"> </textarea>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card>
            <div slot="header">
              <el-button>运行结果</el-button>
            </div>
            <div class="card_body" v-html="htmlSourceCode"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
//引入录音
import Record from "@/utils/record-sdk";
//引入全局实例
import codeMirror from "codemirror";
//核心样式
import "codemirror/lib/codemirror.css";
//语法高亮
import "codemirror/mode/htmlmixed/htmlmixed.js";
import "jquery/dist/jquery.js";
import "codemirror/mode/javascript/javascript.js";
import "codemirror/mode/css/css.js";
import PageHeader from "../page-header.vue";
import axios from "axios";
const CodeMirror = window.CodeMirror || codeMirror;
export default {
  components: { PageHeader },
  data() {
    return {
      progress: 0,
      progressData: 0,
      htmlSourceCode:
        "<!DOCTYPE html>\n" +
        "<html>\n" +
        "<head>\n" +
        '<meta charset="utf-8">\n' +
        "<title>菜鸟教程(runoob.com)</title>\n" +
        "</head>\n" +
        "<body>\n" +
        "\n" +
        "<h1>我的第一个标题</h1>\n" +
        "<p>我的第一个段落。</p>\n" +
        "\n" +
        "" +
        "</body>\n" +
        "</html>", // html代码
      editorCodeMirror: null, // HTML编辑器文本域
      courseInfoList:[],   //code列表
      // codeIndex:'',  //code列表下标
      ifDisplay: false, //是否播放
      isFinished: false, //是否录制完成
      audio: "", //音频
      recorder: new Record(), //新建录音
      chapterId: "",
      blobFile: "", //音频文件
      socket: null, //websocet
      startTime: null, //开始时间
      nowTime: null, //当前时间
      totalTime: null, //总时间
      ifRun: false, //是否点击运行
    };
  },
  mounted() {
    //初始化编辑器
    this.initCodeMirror();
  },
  computed:{
    codeIndex :function(){
      this.editorCodeMirror.setValue(this.courseInfoList[this.codeIndex].htmlCode);
      this.editorCodeMirror.refresh()
      this.progress = parseInt(this.courseInfoList[this.codeIndex].time / this.totalTime)*100
      return this.courseInfoList.indexOf(this.courseInfoList.filter((d) => d.time == parseInt(this.audio.currentTime*1000) )[0])
    }
  },
  methods: {
    init(id) {
      //id是章节id
      this.chapterId = id;
    },
    goBack() {
      this.$emit("backContentShow");
    },
    // 初始化编辑器实例，传入需要被实例化的文本域对象和默认配置
    initCodeMirror() {
      this.editorCodeMirror = CodeMirror.fromTextArea(this.$refs.HtmlEditor, {
        mode: "text/html", // 选择对应代码编辑器的语言
        tabSize: 2, // 缩进格式
        lineNumbers: true, // 显示行号
        line: true,
      });
      this.editorCodeMirror.setSize("100%", "700px"); // 设置编辑器大小
      this.editorCodeMirror.setValue(this.htmlSourceCode);
    },
    //初始化websocket
    initWebsocket() {
      this.socket = new WebSocket(
        `ws://localhost:8080/renren-fast/websocket/chapterContent/${this.chapterId}`
      );
      this.socket.onopen = this.websocketOnopen;
      this.socket.onerror = this.websocketOnerror;
      this.socket.onmessage = this.websocketOnmessage;
      this.socket.onclose = this.websocketOnclose;
    },
    //websocket连接
    websocketOnopen() {
      console.log("WebSocket连接成功");
    },
    //websocket连接失败
    websocketOnerror() {
      console.log("WebSocket连接发生错误");
    },
    //websocket接收消息
    websocketOnmessage(e) {
      console.log(e.data, "接收信息");
      // let data = JSON.parse(e.data);
    },
    //websocket连接关闭
    websocketOnclose() {
      console.log("webSocket断开");
    },
    runHtml() {
      // 运行html
      let that = this;
      this.htmlSourceCode = this.editorCodeMirror.getValue();
      if (this.isFinished) {
        //录课时点击运行按钮
        that.nowTime = new Date() - that.startTime;
        that.ifRun = true;
        //  console.log('now',nowTime)
        let param = {
          chapterId: that.chapterId,
          htmlCode: that.editorCodeMirror.getValue(),
          time: that.nowTime,
          ifRun: that.ifRun,
        };
        that.socket.send(JSON.stringify(param));
      }
    },
    // 开始录制
    onStartVoice() {
      //初始化websocet
      this.initWebsocket();
      this.isFinished = true;
      this.recorder.startRecord({ //录音
        success: (res) => {},
        error: (e) => {
          this.$toast(e);
        },
      });
      //录编程
      let that = this;
      this.progress = 0;
      this.startTime = new Date();
      this.editorCodeMirror.on("change", function () {
        //编辑器内容改变触发
        that.nowTime = new Date() - that.startTime;
        that.ifRun = false;
        //  console.log('now',nowTime)
        let param = {
          chapterId: that.chapterId,
          htmlCode: that.editorCodeMirror.getValue(),
          time: that.nowTime,
          ifRun: that.ifRun,
        };
        that.socket.send(JSON.stringify(param));
      });
    },

    // 结束录音
    onEndVoice() {
      this.isFinished = false;
      this.socket.onclose(); //关闭连接
      let endTime = new Date();
      this.totalTime = endTime - this.startTime;
      this.recorder.stopRecord({
        success: (res) => {
          //此处可以获取音频源文件(res)，用于上传等操作
          console.log("音频源文件", res);
          this.blobFile = res;
        },
      });
    },


    // 播放录音
    onPlayAudio() {
      if (this.isFinished) {
        this.$message.warning("正在录制");
      } else {
        this.ifDisplay = true;
        this.audio = document.getElementById("audioVoice");
        if (!this.audio.currentTime) {
          this.recorder.play(this.audio);
          console.log(this.audio,'this.audio')
        } else {
          this.audio.play();
        }
      }
    },
   //获得code列表
    getCodeList(){
      this.$http({
         url:this.$http.adornUrl(''),
        method:'get',
        params:this.$http.adornParams({
          chapter_id:this.chapterId
        })
      }).then(({data})=>{
        if(data&&data.code === 0){
             this.courseInfoList = data.data
           }else{
             this.$message(data.msg)
           }
      })
    },
    // 暂停播放录音
    stopDispaly() {
      this.ifDisplay = false;
      // clearInterval(this.schedule);
      this.palyTime = new Date() - this.startTime
      //暂停音频
      let video = document.getElementById("audioVoice");
      video.pause();
    },

    //上传文件
    uploadFile() {
      var formData = new FormData();
      var blobFileInfo = new File([this.blobFile],'myblob.wav',{type:"audio/wav"});
      //formData.set("name","filename");
      // formData.set("filename", "myblob.zip");
      // formData.append("filename", "blob");
      formData.append("file", blobFileInfo);
      //formData.append("chapterId", this.course_chapter_id,"myblob.zip");
       console.log(this.blobFile, 'file')
      // console.log(formData.get('filename'), 'from')
    
      this.$http({
         url:this.$http.adornUrl('/upload/uploadBlob'),
         headers:{"Content-Type": "multipart/form-data; charset=UTF-8"},
         method:'post',
         data:formData
      }).then(({data})=>{
        if(data&&data.code === 0){
             this.courseInfoList = data.data
           }else{
             this.$message(data.msg)
           }
      })
    },
  },
};
</script>

<style  scoped>
.card_body {
  height: 350px;
}
.container {
  height: 600px;
  width: 98%;
  margin-top: 20px;
}
.course-header {
  display: flex;
  justify-content: space-between;
}
.display {
  margin-top: 10px;
  margin-left: 20px;
  display: flex;
  flex: 1;
  justify-content: space-between;
}
.submitBIN {
  float: right;
}
.tabs {
  font-size: 18px;
}
</style>
